import { editUserInfo } from '../../api/login'
import { getAvatar, setAvatarAndUserInfo } from '../../utils/getAvatar'
import { login, isLogin, setInfo } from '../../utils/login'
import source from '../../utils/city'

Page({

  /**
   * 页面的初始数据
   */
  data: <any>{
    active: 1,
    avatar: '', //头像
    // 用户信息
    userInfo: {
      id: ''
    },
    // 医生和职业
    fieldType: "",
    docker: "",
    defaultAvatar: "",
    // 城市
    showCityPicker: false,
    provinceName: [],
    provinceCode: [],
    cityName: '',
    cityCode: '',
    cityValue: ['', ''],
    formInfo: {
      name: '',
      province: '',
      city: '',
      position: '',
      hospital: '',
      card: [],
      fileList: []
    }
  },

  onLoad(){
    if(!isLogin()){
      this.setData({
        avatar: getApp().globalData.defaultAvatar
      })
    }
    this.init()
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow(){
    if (typeof this.getTabBar === 'function' && this.getTabBar()) {
      this.getTabBar().setData({
        selected: 3
      })
    }

    this.init()
  },

  handleLogin(){
    const userInfo = login()
    if(userInfo){
      this.handleLoginAction(userInfo);
      this.getAvatarHandle()
      this.setData({
        formInfo: {
          name: userInfo.name,
          province: userInfo.province,
          city: userInfo.city,
          position: userInfo.position,
          hospital: userInfo.hospital,
          card: userInfo.card,
          fileList: userInfo.fileList || []
        }
      })
    }
  },

  init(){
    if(isLogin()){
      const userInfo = login()
      if(userInfo){
        this.handleLoginAction(userInfo);
        this.getAvatarHandle()
        this.setData({
          formInfo: {
            name: userInfo.name,
            province: userInfo.province,
            city: userInfo.city,
            position: userInfo.position,
            hospital: userInfo.hospital,
            card: userInfo.card,
            fileList: userInfo.fileList || []
          }
        })
      }

      this.setSource()
    }
  },

  handleLoginAction(userInfo: any){
    this.setData({
      userInfo: userInfo,
      logined: true,
    })
  },

  getAvatarHandle() {
    if (this.data.avatar) {
      return
    }
    const avatar = getAvatar(this)
    this.setData({
      avatar
    })
  },

  // 点击切换 
  selectbtn(event: any) {
    let index = event.currentTarget.dataset.index
    this.setData({
      active: index
    })

    // 绑定分享参数
    wx.onCopyUrl(() => {
      return { query: `active=${this.data.active}` }
    })
  },

  chosePicture() {
    wx.chooseMedia({
      count: 5,
      mediaType: ['image'], 
      sourceType: ['album', 'camera'],
      camera: 'back',
      success: (res) => {
        const tempFiles = res.tempFiles
        const promises = tempFiles.map((file) => {
          return this.uploadFile(file.tempFilePath)
        });
        
        Promise.all(promises).then(res => {
          const newFileList = [...this.data.formInfo.fileList]; 
          res.forEach(item => {
            newFileList.push(item.url)
          })
          this.setData({
            formInfo: {
              ...this.data.formInfo,
              fileList: newFileList
            }
          });
        })
      }
    });
  },

  delPicture(e: any){
    if(this.data.userInfo.status === '1'){
      return 
    }
    const file = e.currentTarget.dataset.file;
    this.setData({
      formInfo: {
        ...this.data.formInfo,
        fileList: this.data.formInfo.fileList.filter(item => item !== file)
      }
    })
  },

  uploadFile(filePath: string){
    return new Promise((resolve, reject) => {
      wx.uploadFile({
        url: 'https://caca.zn-care.com/api/common/upload', // 开发者服务器接口地址
        filePath,
        name: 'file',
        header: {
          Authorization:  `Bearer ${wx.getStorageSync('token')}`
        },
        success: uploadResult => {
          const data = uploadResult.data
          const jsonRes = JSON.parse(data)
          const { url, fileName } = jsonRes
          if(url){
            resolve({
              url, 
              fileName
            })
          }
        },
        fail: uploadError => {
          wx.hideLoading()
          wx.showToast({
            title: '上传出错',
            icon: 'error',
            duration: 2000,
          })
          reject(uploadError);
        }
      });
    })
  },

  onChooseAvatar(e: any) {
    const { avatarUrl } = e.detail
    wx.uploadFile({
      url: 'https://caca.zn-care.com/api/common/upload', // 开发者服务器接口地址
      filePath: avatarUrl,
      name: 'file',
      header: {
        Authorization:  `Bearer ${wx.getStorageSync('token')}`
      },
      success: uploadResult => {
        const data = uploadResult.data
        const jsonRes = JSON.parse(data)
        const { url } = jsonRes
        if(url){
          setAvatarAndUserInfo(url, this, this.data.userInfo)
          this.updateUserInfo()
        }
      },
      fail: uploadError => {
        console.error(uploadError);
      }
    });
  },

  updateUserInfo(){
    if(!this.data.userInfo.id || !this.data.avatar){
      return;
    }
    editUserInfo({
      id: this.data.userInfo.id,
      avatar: this.data.avatar
    }).then(res => {
      wx.showToast({
        title: '更新成功',
        icon: 'success'
      });
    })
  },

  setSource: function (pro: number = 0) {
    let province: any = source['100000']
    let provinceName: never[] = [];
    let provinceCode: string[] = [];
    for (let item in province) {
      provinceName.push(province[item]);
      provinceCode.push(item);
    }
    this.setData({
      provinceName,
      provinceCode
    })
    let city: any = source[provinceCode[pro]];
    let cityName = [];
    let cityCode = [];
    for (let item in city) {
      cityName.push(city[item]);
      cityCode.push(item);
    }
    this.setData({
      cityName: cityName,
      cityCode: cityCode
    });
  },
  pickerChange: function (e: any) {
    let [province, city] = e.detail.value;
    this.setSource(province);
    this.setData({
      cityValue: [this.data.provinceName[province], this.data.cityName[city]]
    })
  },
  choseCity: function () {
    this.setData({
      showCityPicker: true
    })
  },
  cancel: function () {
    this.setData({
      showCityPicker: false
    });
  },
  sure: function () {
    this.setData({
      formInfo: {
        ...this.data.formInfo,
        province: this.data.cityValue[0] || source['100000'][110000],
        city: this.data.cityValue[1] || source['110000'][110100],
      }
    });
    this.cancel();
  },
  formSubmit: function(e: any){
    let isEmpty = false;
    let formData = e.detail.value;

    for (let key in formData) {
      if (formData[key] === '') {
        isEmpty = true;
        break;
      }
    }

    if (isEmpty) {
      wx.showToast({
        title: '请补充信息',
        icon: 'none'
      });
      return;
    }

    // 提交时使用 files 字段
    const data = {
      ...formData,
      id: this.data.userInfo.id,
      files: JSON.stringify(this.data.formInfo.fileList)
    }

    editUserInfo(data).then(res => {
      wx.showToast({
        title: '更新成功',
        icon: 'success'
      });

      const info = {
        ...this.data.userInfo,
        ...formData,
        fileList: this.data.formInfo.fileList // 保持 fileList 字段
      }

      setInfo(info, this)
    }).catch(e => {
      console.log(e)
    })
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    return {
      "title": "",
      "path": `pages/home/home?active=1`,
      "imageUrl": "/static/img/home.jpg"
    }
  }
})